import { init } from 'snabbdom/build/package/init'
import { h } from 'snabbdom/build/package/h'

// 导入模块
import { datasetModule } from 'snabbdom/build/package/modules/dataset'
import { classModule } from 'snabbdom/build/package/modules/class'
import { attributesModule } from 'snabbdom/build/package/modules/attributes'
import { propsModule } from 'snabbdom/build/package/modules/props'
import { styleModule } from 'snabbdom/build/package/modules/style'
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners'

// 注册模块
const patch = init([
  datasetModule,
  classModule,
  attributesModule,
  propsModule,
  styleModule,
  eventListenersModule,
])

const app = document.querySelector('#app')

let topThreeMovies = [
  {
    rank: 1,
    name: '肖申克的救赎',
    time: 1994,
    rating: 2292974,
  },
  {
    rank: 2,
    name: '霸王别姬',
    time: 1993,
    rating: 1701007,
  },
  {
    rank: 3,
    name: '阿甘正传',
    time: 1994,
    rating: 1724454,
  },
]

let vnode = renderBody()

function renderBody() {
  return h('div', [
    h('h1', {}, '豆瓣电影 Top 3'),
    h('div', [
      h('span', {}, '排序：'),
      h(
        'button',
        {
          style: { marginRight: '10px' },
          on: {
            click: () => {
              handleSort('rank')
            },
          },
        },
        '排名'
      ),
      h(
        'button',
        {
          style: { marginRight: '10px' },
          on: {
            click: () => {
              handleSort('rating')
            },
          },
        },
        '评价人数'
      ),
      h(
        'button',
        {
          on: {
            click: () => {
              handleSort('time')
            },
          },
        },
        '上映时间'
      ),
    ]),
    h('ul.movie-list', {}, renderList()),
  ])
}

function renderList() {
  let arr = [
    h('li.movie-list-item', [
      h('span.movie-list-rank', {}, '排名'),
      h('span.movie-list-name', {}, '电影'),
      h('span.movie-list-time', {}, '上映时间'),
      h('span.movie-list-rating', {}, '评价人数'),
    ]),
  ]
  topThreeMovies.forEach(item => {
    arr.push(
      h('li.movie-list-item', [
        h('span.movie-list-rank', {}, item.rank),
        h('span.movie-list-name', {}, item.name),
        h('span.movie-list-time', {}, item.time),
        h('span.movie-list-rating', {}, item.rating),
      ])
    )
  })
  return arr
}

vnode = patch(app, vnode)

function handleSort(type) {
  switch (type) {
    case 'rank':
      topThreeMovies.sort((a, b) => a.rank - b.rank)
      break
    case 'rating':
      topThreeMovies.sort((a, b) => b.rating - a.rating)
      break
    case 'time':
      topThreeMovies.sort((a, b) => a.time - b.time)
      break
  }
  vnode = patch(vnode, renderBody())
}
